import { Col, Empty, Form, Spin, Tabs } from 'antd';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ContractHomeContext } from '../../../common';
import { reportStateByStepService } from '../services';
import pageStyles from '@/common/pageLayout.less';
import ReactDOM from 'react-dom';
import Cls from 'classnames';
import * as echarts from 'echarts';
import { useEchartsDataReport } from '../mconfig/useEchartsData';
import _ from 'lodash';
import { IContractHPActionEnum } from '../../../common/useReducer';

import { ContractCountCollecRight } from './ContractCountCollecRight';
import { ContractCountCollecLeftHeard } from './ContractCountCollecLeftHeard';
import { getPersonalInfo } from '@/utils';

export const ContractCountCollec: React.FC = () => {
  /**引入上下文 */
  const { styleFixCls, curRes, dispatch } = useContext(ContractHomeContext);

  /** 空 */
  const [isShowEm, setIsShowEm] = useState<boolean>(false);

  const [cloneResult, setCloneResult] = useState();
  /**回调函数 */
  const countCallback = (res: any) => {
    if (res?.msgFlag) {
      // =====================返回数据变化 不需要处理
      // const result = useEchartsDataReport(res?.obj, '0');
      // console.log(result);
      if (res?.obj?.length) {
        setIsShowEm(false);
        setCloneResult(res?.obj);
        renderLineChart(res?.obj);
      } else {
        setIsShowEm(true);
      }
      dispatch({ type: IContractHPActionEnum.set_collectionData, payload: res?.obj });
    }
  };

  /** 折线图Ref */
  let receivableRef: any = useRef();
  // 状态
  let purchaseState = ['待编制', '文件编制中', '待实施', '澄清中', '待开标', '已开标', '已完成', '流标', '待完成'];
  //引入统计接口
  const { reportAllByDateStepLoading, reportAllByDateStepRun } = reportStateByStepService(curRes, countCallback);

  /** 刷新 */
  const tabsExtraBtns = () => {
    return <ContractCountCollecLeftHeard reportAllByDateStepRun={reportAllByDateStepRun} />;
  };

  /**
   * 处理柱状图鼠标移入气泡
   * @param params
   * @returns
   */
  const renderTooltip = (params: Record<string, any>[], data) => {
    let tipStr: string = `${params?.[0]?.name}`;
    const resObj = data?.find((item) => item?.name == tipStr);
    params?.forEach((item) => {
      tipStr += ` 
            <br />
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#469e53;"></span>1111 : ${resObj?.totalPaid}元
            <br />
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#ccc;"></span>未收金额 : ${resObj?.totalResidue}元
            <br />
            ${params?.[0]?.marker}应收金额 : ${resObj?.totalSum}元
            `;
    });
    return tipStr;
  };

  /** 渲染折线图 */
  const renderLineChart = (data) => {
    // 获取当前状态的数据

    let info: any = [];
    data.forEach((item: any) => {
      info.push({
        searchStateName: item?.searchStateName,
        searchState: item?.searchState,
        totalNum: item?.totalNum,
        expectAllSum: item?.expectAllSum,
      });
    });
    if (receivableRef?.current) {
      const putStateViewDiv: any = ReactDOM.findDOMNode(receivableRef?.current);
      const myChart = echarts.init(putStateViewDiv);
      // let maxObj = getMaxObj(data);
      const option = {
        title: {
          text: '采购状态汇总统计',
          left: 'center',
        },
        toolbox: {
          feature: {
            magicType: { show: true, type: ['line', 'bar'] },
          },
        },
        legend: {
          data: ['金额', '数量'],
          padding: [30, 5],
        },
        xAxis: {
          type: 'category',
          data: info?.map((item: any) => item?.searchStateName),
        },
        yAxis: [
          {
            type: 'value',
            name: '金额/元',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
            },
          },
          {
            type: 'value',
            name: '数量/个',
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: true,
            },
          },
        ],
        tooltip: {
          trigger: 'axis',
        },
        series: [
          {
            name: '金额',
            data: info?.map((item) => item?.expectAllSum),
            type: 'line',
            yAxisIndex: 0,
          },
          {
            name: '数量',
            data: info?.map((item) => item?.totalNum),
            type: 'line',
            yAxisIndex: 1,
          },
        ],
      };
      myChart.setOption(option as any);
    }
  };

  /** tab配置 */
  const tabsItem = useMemo(() => {
    return [
      {
        label: '状态统计',
        key: '1',
        children: isShowEm ? (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <div className={`${styleFixCls}RootDiv-echartBoxDiv`} ref={receivableRef} style={{ height: '100%', width: '100%' }}></div>
        ),
      },
    ];
  }, [curRes, receivableRef, isShowEm]);

  /*
  useEffect(() => {
    // 窗口大小变化时重新渲染图表
    const handleResize = () => {
      if (receivableRef.current) {
        const chartInstance = echarts.getInstanceByDom(receivableRef.current);
        if (chartInstance) {
          chartInstance.resize();
        } 
        // else {
        //   renderLineChart(cloneResult);
        // }
      }
    };

    // 添加窗口大小变化事件监听器
    window.addEventListener('resize', handleResize);

    // 组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // 仅在组件挂载时执行一次，使用空数组作为依赖项，以确保只在组件挂载时执行一次
  */
  return (
    <>
      <Col span={16} className={styleFixCls + 'RootDiv-ColSpanB'}>
        <Spin spinning={reportAllByDateStepLoading}>
          <div className={Cls(pageStyles['commonTabsLine'])} style={{ height: '100%', width: '100%' }}>
            <Tabs tabBarExtraContent={tabsExtraBtns()} items={tabsItem} />
          </div>
        </Spin>
      </Col>

      <ContractCountCollecRight countLoading={reportAllByDateStepLoading} />
    </>
  );
};
